package com.suixun.handler;

import com.authority.result.BasicResult;
import com.suixun.APIException;
import com.suixun.Result;
import com.suixun.enums.APICode;
import com.suixun.exception.OpServiceException;

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Map;

/**
 * ApiHandlerExceptionResolver.java 异常处理，所有的异常都拦截到这里做统一处理
 * 
 * @author <a href="mailto:huangy@17find.com">hellmash</a>
 * @version create on 2015-07-17 17:41
 *          <p>
 *          CopyRight(c)2015 杭州随寻科技有限公司 17find.com 版权所有
 */
public class ApiHandlerExceptionResolver extends SimpleMappingExceptionResolver {

    private Logger logger = LoggerFactory.getLogger(ApiHandlerExceptionResolver.class);

    @Override
    protected ModelAndView doResolveException(HttpServletRequest request,
            HttpServletResponse response, Object handler, Exception ex) {

        String requestURI = request.getRequestURI();
        Map<String, String[]> params = request.getParameterMap();
        String queryString = "";
        if(params != null)
            queryString = params.size() + " params->";
        try{
        for (String key : params.keySet()) {
            String[] values = params.get(key);
            for (int i = 0; i < values.length; i++) {
                String value = values[i];
                queryString += key + "=" + value + "&";
            }
        }}catch (Exception e) {
            // TODO: handle exception
        }
        if (logger.isDebugEnabled())
            logger.debug("OPException: " + ex.getMessage() + ",requestUrl： " + requestURI + "callPath: "
                    + queryString, ex);
        logger.error(request.getHeader("User-Agent"));
        logger.error("OPException: " + ex.getMessage() + ",requestUrl： " + requestURI + "callPath: " + queryString,
                ex);

        try {
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
            PrintWriter out = response.getWriter();
            String json = null;
            response.setStatus(APICode.HTTP_200.getCode());
            // 针对APIException
            if (ex instanceof APIException) {
                APIException apiException = (APIException) ex;
                // response.setStatus(apiException.getApiCode().getCode());
                json = objectMapper.writeValueAsString(new Result(apiException.getApiCode(), null));
            } else if(ex instanceof OpServiceException) {
            	BasicResult<Void> result = new BasicResult<>();
            	result.setCode(500);
            	result.setMsg(ex);
            	json = objectMapper.writeValueAsString(result);
            } else {
                json =
                        objectMapper.writeValueAsString(new Result(APICode.HTTP_500
                                .setCustomMsg("服务器发生错误,请稍后再操作"), null));
            }
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            out.write(json);
            out.close();
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return null;
    }
}
